//
//  SINAStuActivityAddTargetThreeViewController.m
//  PlanTech
//
//  Created by  androidlongs on 2018/7/9.
//  Copyright © 2018年  androidlongs. All rights reserved.
// 小目标 第三版
//

#import "SINAStuActivityAddTargetThreeViewController.h"
#import "SINAStuActivityAddTargetInputViewController.h"
#import "XLCardSwitch.h"
#import "SINACircularBeadUtils.h"
#import "SINACalendarUtils.h"

@interface SINAStuActivityAddTargetThreeViewController ()<XLCardSwitchDelegate>

@property(nonatomic,strong)  XLCardSwitch *msgCardSwitch;
@property(nonatomic,strong)  UIView *headerView;
@property(nonatomic,strong)  UIView *indexFlagView;
@property(nonatomic,strong)  UIView *delectTarView;
@property(nonatomic,strong) NSMutableArray *targetItemArray;

@property(nonatomic,assign) NSInteger currentSelectIndex;

@end

@implementation SINAStuActivityAddTargetThreeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"#f5f5f5"]];
    
    [self initDataFunction];
    [self initViewFunction];
    [self msgCardFunction];
    [self updateIndexFlagFunction];
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    
    [self loadingNetData];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidDisappear:(BOOL)animated{
    for (NSTimer *timer in self.msgCardSwitch.timerSet){
        if (timer!=nil) {
            [timer invalidate];
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"closeTimer" object:nil];
}
-(void)initDataFunction{
    DLog(@"初始化小目标数据");
    self.targetItemArray = [[NSMutableArray alloc]init];
    [self.targetItemArray removeAllObjects];
    if (self.targetArray==nil||self.targetArray.count==0) {
        //无数据页面
        XLCardItem *item = [[XLCardItem alloc]init];
        item.actTargetModel = nil;
        [self.targetItemArray addObject:item];
    }else{
        //有数据页面
        for (NSInteger i=0; i<self.targetArray.count; i++) {
            SINAStuActivityTargetModel *model = self.targetArray[i];
            XLCardItem *item = [[XLCardItem alloc]init];
            item.actTargetModel = model;
            [self.targetItemArray addObject:item];
        }
    }
    
    self.msgCardSwitch.items=self.targetItemArray;
    [self updateIndexFlagFunction];
    
}

-(void)updateIndexFlagFunction{
    
    DLog(@"更新显示效果");
    [self.indexFlagView removeAllSubviews];
    if (self.targetArray==nil||self.targetArray.count==0) {
        self.indexFlagView.hidden=YES;
    }else{
        self.indexFlagView.hidden=NO;
        NSInteger flagCount =self.targetArray.count;
        if (flagCount>5) {
            flagCount=5;
        }
        
        NSInteger itemWidth=14;
        NSInteger startX=0;
        startX = CGRectGetWidth(self.indexFlagView.frame)/2-itemWidth*(flagCount-1)-itemWidth/2;
        
        
        
        for (NSInteger i=0; i<flagCount; i++) {
            
            
            
            UILabel *itemLabel = [[UILabel alloc]initWithFrame:CGRectMake(startX+itemWidth*2*i, 0, itemWidth, itemWidth)];
            itemLabel.backgroundColor=[UIColor colorWithHexString:@"#878787"];
            itemLabel.textAlignment=NSTextAlignmentCenter;
            itemLabel.font=[UIFont systemFontOfSize:12];
            [SINACircularBeadUtils makeCircularBead:itemWidth/2 andView:itemLabel];
            
            [self.indexFlagView addSubview:itemLabel];
            
            if (i==self.currentSelectIndex) {
                itemLabel.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
                itemLabel.text=[NSString stringWithFormat:@"%ld",(self.currentSelectIndex+1)];
            }else {
                if (self.currentSelectIndex>=flagCount) {
                    if (i==flagCount-1) {
                        itemLabel.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
                        itemLabel.text=[NSString stringWithFormat:@"%ld",(self.currentSelectIndex+1)];
                    }
                }
            }
        }
        
    }
}
-(void)initViewFunction{
    
    
    UIImageView *backgroundImageView = [[UIImageView alloc]init];
    backgroundImageView.frame = CGRectMake(0, 0, mainW, mainH);
    backgroundImageView.image = [UIImage imageNamed:@"target_bg"];
    [self.view addSubview:backgroundImageView];
    
    
    UIView *headerView = [[UIView alloc]init];
    [self.view addSubview:headerView];
    self.headerView = headerView;
    headerView.backgroundColor=[UIColor clearColor];
    
    
    
    if (IS_IPHONE_X) {
        headerView.frame= CGRectMake(0, 0, mainW, 88);
    } else {
        headerView.frame= CGRectMake(0, 0, mainW, 64);
    }
    
    
    UIView *titleView = [[UIView alloc]init];
    [headerView addSubview:titleView];
    titleView.frame=CGRectMake(0, 0, mainW, CGRectGetHeight(headerView.frame));
    titleView.backgroundColor=[UIColor clearColor];
    [headerView addSubview:titleView];
    
    UILabel *titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(titleView.frame)-32, mainW, 22)];
    titleLabel.text=@"小目标";
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.font=[UIFont systemFontOfSize:20];
    titleLabel.textColor=[UIColor whiteColor];
    [titleView addSubview:titleLabel];
    
    UIView *backView = [[UIView alloc]init];
    [headerView addSubview:backView];
    backView.frame=CGRectMake(0, 0, 100, CGRectGetHeight(headerView.frame));
    backView.backgroundColor=[UIColor clearColor];
    
    UIImageView *backImageView = [[UIImageView alloc]init];
    backImageView.frame=CGRectMake(14, CGRectGetHeight(backView.frame)-12-20, 12, 20);
    backImageView.image=[UIImage imageNamed:@"back1"];
    [backView addSubview:backImageView];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:backView andWithBlick:^(UIView *view) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    
    UIView *addTargetView = [[UIView alloc]init];
    [headerView addSubview:addTargetView];
    addTargetView.frame=CGRectMake(mainW-100, 0, 100, CGRectGetHeight(headerView.frame));
    addTargetView.backgroundColor=[UIColor clearColor];
    
    UIImageView *addTargetImageView = [[UIImageView alloc]init];
    addTargetImageView.frame=CGRectMake(CGRectGetWidth(addTargetView.frame)-12-20, CGRectGetHeight(backView.frame)-12-20, 20, 20);
    addTargetImageView.image=[UIImage imageNamed:@"tag_whited_add_icon"];
    [addTargetView addSubview:addTargetImageView];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:addTargetView andWithBlick:^(UIView *view) {
        DLog(@"添加");
        //[self.navigationController popViewControllerAnimated:YES];
        [self toAddTargetPageFunction];
        
    }];
    
//    NSInteger activityStartTime = [self.activityMmodel.activityStartTime integerValue];
    NSInteger activityEndTime = [self.activityMmodel.activityStopTime integerValue];
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    if (currentTime<=(activityEndTime+30*60*1000)) {
        //未超时
        addTargetView.hidden=NO;
    }else{
        //已超时
        addTargetView.hidden=YES;
    }
    
    
    
    
    //设置消息卡片浏览器
    self.msgCardSwitch = [[XLCardSwitch alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame)-20,mainW , mainH-CGRectGetMaxY(self.headerView.frame)-60)];
    
    self.indexFlagView= [[UIView alloc] initWithFrame:CGRectMake(40, CGRectGetMaxY(self.msgCardSwitch.frame)-10,mainW-80 , 20)];
    self.indexFlagView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:self.indexFlagView];
    
    self.delectTarView=[[UIView alloc] initWithFrame:CGRectMake(60, CGRectGetMaxY(self.msgCardSwitch.frame)-35,mainW-120 , 60)];
    self.delectTarView.backgroundColor=[UIColor clearColor];
    self.delectTarView.hidden=YES;
    self.msgCardSwitch.activityMmodel=self.activityMmodel;
    self.msgCardSwitch.timerSet = [[NSMutableSet alloc] init];
    [self.view addSubview:self.delectTarView];
    
    //delect_target_icon
    //45
    UIImageView *deleteTargetImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.delectTarView.frame)/2-45/2, CGRectGetHeight(self.delectTarView.frame)/2-45/2, 45, 45)];
    deleteTargetImageView.image = [UIImage imageNamed:@"delect_target_icon"];
    [self.delectTarView addSubview:deleteTargetImageView];
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.delectTarView andWithBlick:^(UIView *view) {
        DLog(@"删除小目标");
        [self delectTargetFunction];
    }];
}
-(void)toAddTargetPageFunction{
    
//    NSInteger activityStartTime = [self.activityMmodel.activityStartTime integerValue];
    NSInteger activityEndTime = [self.activityMmodel.activityStopTime integerValue];
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    if (currentTime<=(activityEndTime+30*60*1000)) {
        //未超时
        //添加小目标
        SINAStuActivityAddTargetInputViewController *inputController = [[SINAStuActivityAddTargetInputViewController alloc] initWithNibName:@"SINAStuActivityAddTargetInputViewController" bundle:nil];
        inputController .model  =  self.activityMmodel;
        [self.navigationController pushViewController:inputController animated:YES];
    }else{
        //已超时
        [YPXToastView showToastViewWithText:@"活动已结束 不可添加小目标" andDuration:3 andParentView:self.view];
    }
    
}
-(void) msgCardFunction{
    
    WeakSelf;
    
    self.msgCardSwitch.isAnimation =YES;
    //类型页面为 小目标
    self.msgCardSwitch.pagetype=CARDACTIVITYTARGET;
    self.msgCardSwitch.items = self.targetItemArray;
    self.msgCardSwitch.delegate = self;
    //分页切换
    self.msgCardSwitch.pagingEnabled = true;
    //设置初始位置，默认为0
    self.msgCardSwitch.selectedIndex = 0;
    
    [self.view addSubview:self.msgCardSwitch];
    
    
    
    self.msgCardSwitch.switchItemClickBlock = ^(UIView *view, NSInteger index) {
        DLog(@"msg item click index  is %ld",(long)index);
        
        
        if (index==0) {
            //添加页面
            [weakSelf toAddTargetPageFunction];
        } else {
            XLCardItem *item = weakSelf.targetItemArray[weakSelf.currentSelectIndex];
            SINAStuActivityTargetModel *actTargetModel =item.actTargetModel;
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            [dict setObject:actTargetModel.uuid forKey:@"uuid"];
            
            if (index==1) {
                DLog(@"开始小目标");
                NSString *currentStratTime =[SINACalendarUtils currentTimeStr];
                [dict setObject:currentStratTime forKey:@"starttime"];
                [dict setObject:[NSString stringWithFormat:@"%d",1011] forKey:@"status"];
                [weakSelf updateTargetTime:dict andWithFlag:1];
            }else if(index==2){
                //活动结束点击开始小目标
                [YPXToastView showToastViewWithText:@"活动已结束" andDuration:2 andParentView:weakSelf.view];
            }else if(index==3){
                DLog(@"暂停小目标");
                [dict setObject:[NSString stringWithFormat:@"%d",1013 ] forKey:@"status"];
                //pausetime
                [dict setObject:[NSString stringWithFormat:@"%ld",actTargetModel.useTime] forKey:@"pausetime"];
                [weakSelf updateTargetTime:dict andWithFlag:3];
            }else if(index==4){
                DLog(@"暂停->重新开始小目标");
                [dict setObject:[NSString stringWithFormat:@"%d",1012  ] forKey:@"status"];
                [dict setObject:[SINACalendarUtils currentTimeStr] forKey:@"pauseendtime"];
                [weakSelf updateTargetTime:dict andWithFlag:4];
            }else if(index==5){
                DLog(@"完成小目标");
                [dict setObject:[NSString stringWithFormat:@"%d",1014  ] forKey:@"status"];
                [dict setObject:[SINACalendarUtils currentTimeStr] forKey:@"endtime"];
                [dict setObject:[NSString stringWithFormat:@"%ld",actTargetModel.useTimes] forKey:@"pausetime"];
                [weakSelf finishTargetFunction:dict];
            }else if(index==6){
                [YPXToastView showToastViewWithText:@"活动已结束" andDuration:2 andParentView:weakSelf.view];
            }else if(index==7){
                [YPXToastView showToastViewWithText:@"活动未开始" andDuration:2 andParentView:weakSelf.view];
            }else if(index==8){
                [YPXToastView showToastViewWithText:@"活动已结束" andDuration:2 andParentView:weakSelf.view];
            }
        }
        
    };
    
    self.msgCardSwitch.switchItemSwipeBlock = ^(UIView *view, NSInteger index) {
        if (index==1) {
            DLog(@"向上");
            //隐藏角标 显示删除
            if (self.indexFlagView.hidden==NO&&self.indexFlagView.alpha==1.0) {
                weakSelf.delectTarView.hidden=NO;
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.indexFlagView.alpha=0.0;
                    weakSelf.delectTarView.alpha=1.0;
                } completion:^(BOOL finished) {
                    weakSelf.indexFlagView.hidden=YES;
                }];
            }
        } else {
            DLog(@"向下");
            //显示角标 隐藏删除
            if (self.delectTarView.hidden==NO&&self.delectTarView.alpha==1.0) {
                weakSelf.indexFlagView.hidden=NO;
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.indexFlagView.alpha=1.0;
                    weakSelf.delectTarView.alpha=0.0;
                } completion:^(BOOL finished) {
                    weakSelf.delectTarView.hidden=YES;
                    weakSelf.indexFlagView.alpha=1.0;
                }];
            }
        }
    };
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

//删除小目标功能
-(void) delectTargetFunction{
    if (self.currentSelectIndex<self.targetArray.count) {
        SINAStuActivityTargetModel *model=self.targetArray[self.currentSelectIndex];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:model.uuid forKey:@"uuid"];
        
        WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:@"删除小目标？" sureBtn:@"确定" cancleBtn:@"取消"];
        alertView.resultIndex = ^(NSInteger index) {
            NSInteger activityStartTime = [self.activityMmodel.activityStartTime integerValue];
            NSInteger activityEndTime = [self.activityMmodel.activityStopTime integerValue];
            //当前时间
            NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
            
            if (currentTime<activityStartTime) {
                DLog(@"活动未开始");
            }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
                DLog(@"活动中");
            }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
                //活动结束 以及结束后的半小时
            }else{
                //超时
                [YPXToastView showToastViewWithText:@"活动已结束 不可删除小目标" andDuration:2 andParentView:self.view];
                [self hindDeleteTargetFunction];
                return ;
            }
            [self deleteTargetFunction:dict];
        };
        [alertView showXLAlertView];
    }
    
}

-(void) hindDeleteTargetFunction{
    WeakSelf;
    if (self.delectTarView.hidden==NO&&self.delectTarView.alpha==1.0) {
        weakSelf.indexFlagView.hidden=NO;
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.indexFlagView.alpha=1.0;
            weakSelf.delectTarView.alpha=0.0;
        } completion:^(BOOL finished) {
            weakSelf.delectTarView.hidden=YES;
            weakSelf.indexFlagView.alpha=1.0;
        }];
    }
}

-(void) deleteTargetFunction:(NSMutableDictionary *) dict{
    
    
    [self startLoading];
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityTargetDeleteUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
        
        [weakSelf stopLoading];
        [weakSelf hindDeleteTargetFunction];
        
        if ([code isEqualToString:@"1000"]) {
            //删除成功
            [YPXToastView showToastViewWithText:@"操作成功" andDuration:3 andParentView:self.view];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf loadingNetData];
            });
        }else{
            NSString *message =responseData[@"message"];
            [YPXToastView showToastViewWithText:[NSString stringWithFormat: @"操作失败 %@" ,message] andDuration:3 andParentView:self.view];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        [weakSelf hindDeleteTargetFunction];
        [weakSelf stopLoading];
        [YPXToastView showToastViewWithText:@"操作失败 网络异常" andDuration:3 andParentView:self.view];
    }];
}

-(void)loadingNetData{
    
    DLog(@"刷新小目标");
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:[NSString stringWithFormat:@"%d",1] forKey:@"pageIndex"];
    [dict setObject:[NSString stringWithFormat:@"200"] forKey:@"pageSize"];
    [dict setObject:[NSString stringWithFormat:@"%@", [[SINACommonUserHelper share]getUserModel].userUid] forKey:@"receiveruuid"];
    
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?organizeuuid=%@",baseUrl,userActivityTargetListUrl,self.activityMmodel.activityUid] withParamters:dict success:^(id responseData) {
        
        [self.targetArray removeAllObjects];
        NSString *code = responseData[@"code"];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            
            for (NSInteger i=0; i<result.count; i++) {
                NSDictionary *dict = result[i];
                SINAStuActivityTargetModel *model = [[SINAStuActivityTargetModel alloc]initWithDict:dict];
                [self.targetArray addObject:model];
            }
            
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        [self initDataFunction];
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        [self.targetArray removeAllObjects];
        [YPXToastView showToastViewWithText:@"数据加载失败 网络异常" andDuration:2 andParentView:self.view];
        [self initDataFunction];
        
    }];
}

-(void) XLCardSwitchDidSelectedAt:(NSInteger)index{
    self.currentSelectIndex = index;
    DLog(@"当前选中 %ld",index);
    if (index<self.indexFlagView.subviews.count) {
        for (NSInteger i=0; i<self.indexFlagView.subviews.count; i++) {
            UIView *itemView = self.indexFlagView.subviews[i];
            if ([itemView isKindOfClass:[UILabel class]]) {
                UILabel *label=(UILabel*)itemView;
                if (i==index) {
                    label.text=[NSString stringWithFormat:@"%ld",(i+1)];
                    label.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
                }else{
                    label.text=@"";
                    label.backgroundColor=[UIColor colorWithHexString:@"#878787"];
                }
            }
        }
    }else if(index>=self.indexFlagView.subviews.count){
        for (NSInteger i=0; i<self.indexFlagView.subviews.count; i++) {
            UIView *itemView = self.indexFlagView.subviews[i];
            if ([itemView isKindOfClass:[UILabel class]]) {
                UILabel *label=(UILabel*)itemView;
                if (i==self.indexFlagView.subviews.count-1) {
                    label.text=[NSString stringWithFormat:@"%ld",(index+1)];
                    label.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
                }else{
                    label.text=@"";
                    label.backgroundColor=[UIColor colorWithHexString:@"#878787"];
                }
            }
        }
    }
}
//最后在dealloc中遍历set
- (void)dealloc
{
    
}

-(void) updateTargetTime:(NSMutableDictionary *) dict andWithFlag:(NSInteger)flag{
    
    
    [self startLoading];
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityUpdateTargetUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
        
        [weakSelf stopLoading];
        
        if ([code isEqualToString:@"1000"]) {
            
            NSString *message = @"操作成功";
            
            if (flag==1||flag==4) {
                message=@"小目标已开始";
            }else if (flag==3) {
                message=@"小目标已暂停";
            }else if (flag==5) {
                message=@"小目标已完成";
                
                SINAStuActivityTargetModel *actTargetModel = weakSelf.targetArray[weakSelf.currentSelectIndex];
                XLCardItem *item=weakSelf.targetItemArray[weakSelf.currentSelectIndex];
                actTargetModel.status=1014;
                item.actTargetModel.status=1014;
                
                [weakSelf.msgCardSwitch updateWithIndex:weakSelf.currentSelectIndex];
            }
            //添加成功
            [YPXToastView showToastViewWithText:[NSString stringWithFormat:@"%@",message] andDuration:3 andParentView:weakSelf.view];
            
        }else{
            NSString *message =responseData[@"message"];
            [YPXToastView showToastViewWithText:[NSString stringWithFormat: @"操作失败 %@" ,message] andDuration:3 andParentView:self.view];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        [weakSelf stopLoading];
        [YPXToastView showToastViewWithText:@"操作失败 网络异常" andDuration:3 andParentView:self.view];
    }];
}

-(void)finishTargetFunction:(NSMutableDictionary *) dict{
    DLog(@"完成小目标");
    
//    NSString *endTime = [SINACalendarUtils currentTimeStr];
    
    WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:@"结束小目标？" sureBtn:@"确定" cancleBtn:@"取消"];
    alertView.resultIndex = ^(NSInteger index) {
        
        [self updateTargetTime:dict andWithFlag:5];
    };
    [alertView showXLAlertView];
}

@end
